<template>
  <div class="edit-organ-box">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <template v-for="item in formList">
        <el-form-item
          :key="item.prop"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :clearable="true"
            v-bind="item.attrConfig||{}"
            @change="handlerSelectData(item)"
          />
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'

export default {
  name: 'EditOrgan',
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        parentId: null,
        deptName: null,
        deptCode: null,
        leader: null,
        mobilePhone: null,
        email: null,
        remark: null
      },
      formList: [
        { name: '上级机构',
          prop: 'parentId',
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择上级机构',
            'show-all-levels': false,
            props: {
              children: 'children',
              label: 'deptName',
              value: 'id',
              checkStrictly: true,
              emitPath: false,
              expandTrigger: 'hover'
            },
            ref: 'parentId',
            'popper-class': 'cascader-theder',
            options: []
          },
          isClosePop: true
        },
        { name: '机构名称',
          prop: 'deptName',
          attrConfig: { placeholder: '请输入机构名称' }
        },
        { name: '机构编码',
          prop: 'deptCode',
          attrConfig: { placeholder: '请输入机构编码', maxlength: 24 }
        },
        { name: '负责人',
          prop: 'leader',
          attrConfig: { placeholder: '请输入负责人' }
        },
        { name: '手机号码',
          prop: 'mobilePhone',
          attrConfig: { placeholder: '请输入手机号码' }
        },
        { name: '邮箱',
          prop: 'email',
          attrConfig: { placeholder: '请输入邮箱' }
        },
        { name: '备注',
          prop: 'remark',
          itemClass: 'width100p',
          attrConfig: {
            type: 'textarea',
            placeholder: '请输入备注信息',
            maxlength: 500
          }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        leader: [{ required: false, message: '负责人长度过长', max: 24, trigger: 'blur' }],
        deptName: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
        mobilePhone: [{ required: false, trigger: 'blur', validator: this.mobilePhoneValidate }],
        email: [{ required: false, trigger: 'blur', validator: this.emailValidate }]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          this.formList.forEach(e => {
            this.$set(this.formData, e.prop, data[e.prop])
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        ...this.formData || {},
        id: this.popData.id || ''
      }
      this.submit(params)
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    /**
     * 获取机构数据
    */
    getTreeData() {
      this.$api.organManage.queryPage({}).then(res => {
        if (Number(res.code) === 1000) {
          const { records = [] } = res.data || {}
          const treeList = arr2tree(records, { id: 'id', parentId: 'parentId' })
          this.formList.forEach(e => {
            if (e.prop === 'parentId') {
              this.$set(e.attrConfig, 'options', treeList || [])
            }
          })
        } else if (res.msg) {
          this.$message({ type: 'error', message: res.msg })
        }
      })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async(valid) => {
        if (valid) {
          const res = await this.$api.organManage.update(params)
          if (Number(res.code) === 1000) {
            this.$message.success('修改成功!')
            this.$emit('onFinish', 'edit-organ')
          }
        }
      })
    },
    /**
     * 验证手机号
     */
    mobilePhoneValidate(rule, value, callback) {
      const REP = new RegExp(/^1[3456789]\d{9}$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的手机号码!'))
      } else {
        callback()
      }
    },
    /**
     * 验证邮箱
     */
    emailValidate(rule, value, callback) {
      const REP = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的邮箱格式!'))
      } else {
        callback()
      }
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-organ-box {
  color: #333;
  padding: 0 20px;

  .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }
    }

    .el-cascader {
      width: 100%;
    }
  }
}
</style>
